package com.zyk.scaffold.user.mail.sender;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zyk.scaffold.core.domain.Result;
import com.zyk.scaffold.common.utils.AssertUtil;
import com.zyk.scaffold.common.utils.MD5Util;
import com.zyk.scaffold.common.utils.StringUtils;
import com.zyk.scaffold.user.mail.MailApiConstants;
import com.zyk.scaffold.user.mail.properties.ApiConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.security.NoSuchAlgorithmException;

@Slf4j
public class LocalMailApiSender implements ILocalMailSender{

    private RestTemplate restTemplate = new RestTemplate();
    private ApiConfig apiConfig;

    public LocalMailApiSender(ApiConfig apiConfig) {
        this.apiConfig = apiConfig;
    }

    @Override
    public boolean send(SenderMessage senderMessage) {
        if(!valid(senderMessage)){
            log.error("邮件发送,参数校验不通过：{}", JSON.toJSONString(senderMessage));
            AssertUtil.error("邮件发送,参数校验不通过");
        }

        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.APPLICATION_JSON);
        header.add(MailApiConstants.HEADER_MAIL_APP_KEY, this.apiConfig.getAppKey());
        try {
            header.add(MailApiConstants.HEADER_MAIL_APP_SIGN, MD5Util.computeMD5(this.apiConfig.getAppKey() + "-" + senderMessage.toText() + "-" + this.apiConfig.getAppSecret()));
        } catch (NoSuchAlgorithmException e) {
            log.error("邮件发送签名异常,参数：" + JSON.toJSONString(senderMessage), e);
            AssertUtil.error("邮件发送签名异常");
        }
        HttpEntity<SenderMessage> httpEntity = new HttpEntity<>(senderMessage, header);
        try {
            // 通过API发送邮件
            ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(this.apiConfig.getApi(), httpEntity, String.class);
            String body = stringResponseEntity.getBody();
            if(StringUtils.isEmpty(body)){
                return false;
            }
            Result<Boolean> result = JSON.parseObject(body, new TypeReference<Result<Boolean>>() {
            });
            return  result != null && result.getData();
        }catch (Exception e){
            log.error("邮件发送出现异常,参数：" + JSON.toJSONString(senderMessage), e);
            AssertUtil.error("邮件发送出现异常");
        }
        return false;
    }
}
